package dtm

import (
	"context"
	"database/sql"

	// "fmt"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/dtm-labs/client/dtmcli"
	"github.com/dtm-labs/client/dtmgrpc"
	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
)

type UpdatePromotionLogRawLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePromotionLogRawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePromotionLogRawLogic {
	return &UpdatePromotionLogRawLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePromotionLogRawLogic) UpdatePromotionLogRaw(in *promotion.UpdatePromotionLogReq) (*promotion.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("UpdatePromotionLogRaw UpdatePromotionLogReq: %+v", in))
	// UserId:10001 OrderId:8 Logs:{ActivityId:2 ActivityRuleId:2 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:1 ActivityRuleId:1 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:0 ActivityRuleId:0 CouponTemplateId:1 CouponId:1}

	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	if in.OrderId == nil || *in.OrderId == 0 {
		return nil, resultx.StatusError(resultx.ORDER_ID_REQUIRED, "")
	}

	if in.Status == nil || *in.Status == 0 {
		return nil, resultx.StatusError(resultx.PROMOTION_STATUS_INVALID, "")
	}

	if len(in.Logs) == 0 {
		return &promotion.BaseResp{}, nil
	}

	// 获取子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, resultx.StatusError(resultx.DTM_ERROR, err.Error())
	}

	// 开启子事务屏障
	err = barrier.CallWithDB(l.svcCtx.DB, func(tx *sql.Tx) error {
		status := int32(*in.Status)
		now := time.Now()
		usedAt := null.TimeFrom(now)

		for _, v := range in.Logs {
			if v.CouponId != nil && *v.CouponId > 0 {
				coupon, err := l.svcCtx.Coupon.FindOneNoCache(l.ctx, tx, *v.CouponId)
				if err != nil {
					if err == sql.ErrNoRows {
						continue
					}

					return err
				}

				var orderId uint64
				var oprType uint8
				if status == globalkey.StatusUsed {
					coupon.UsedAt = usedAt
					orderId = *in.OrderId
					oprType = uint8(globalkey.CouponOprTypeFreeze)
				} else if status == globalkey.StatusStarted {
					coupon.UsedAt = null.TimeFromPtr(nil)
					oprType = uint8(globalkey.CouponOprTypeUnfreeze)
				}

				coupon.OrderID = orderId
				coupon.Status = uint16(status)
				err = l.svcCtx.Coupon.Update(l.ctx, tx, coupon)
				if err != nil {
					return err
				}

				log := &model.PromotionCouponOprLog{
					CouponID:  *v.CouponId,
					UserID:    *in.UserId,
					Type:      oprType,
					Status:    uint16(globalkey.StatusEnabled),
					CreatedAt: now,
				}
				err = log.Insert(l.ctx, tx, boil.Infer())
				if err != nil {
					logx.Errorw("UpdatePromotionLogRaw PromotionCouponOprLog Insert err", logx.Field("detail", err.Error()))
				}
			} else if v.ActivityId != nil && *v.ActivityId > 0 {
				var oprType uint8
				if status == globalkey.StatusUsed {
					oprType = uint8(globalkey.ActivityOprTypeParticipate)
				}

				log := &model.PromotionActivityLog{
					ActivityID: *v.ActivityId,
					UserID:     *in.UserId,
					OrderID:    *in.OrderId,
					Type:       oprType,
					Status:     uint8(globalkey.StatusEnabled),
					CreatedAt:  now,
				}
				err = log.Insert(l.ctx, tx, boil.Infer())
				if err != nil {
					return resultx.StatusError(resultx.DB_ERROR, "")
				}
			}
		}

		return nil
	})

	// 不再重试，走回滚
	if err == dtmcli.ErrFailure {
		return nil, resultx.StatusError(uint32(codes.Aborted), dtmcli.ResultFailure)
	}

	if err != nil {
		return nil, err
	}

	return &promotion.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
